//
//  RBCategoryTypeView.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/13.
//

#import "RBCategoryTypeView.h"
#import <Masonry.h>
#import "RBThemeConfig.h"
#import "UIView+RBAdd.h"
#import <UIView+YYAdd.h>
#import "RBDefine.h"
#import <UIColor+YYAdd.h>
#import "RBCellProtocol.h"

#define RBCategoryTypeCellNoti @"RBCategoryTypeCellNoti"

@interface RBCategoryTypeModel : NSObject
@property(nonatomic, copy)NSString *title;
@property(nonatomic, assign)NSInteger index;
@property(nonatomic, assign)NSInteger selectedIndex;
@end
@implementation RBCategoryTypeModel
@end

@interface RBCategoryTypeCell : UITableViewCell<RBCellProtocol>

@property(nonatomic, strong)UIView *container;
@property(nonatomic, strong)UIView *lineView;
@property(nonatomic, strong)UILabel *titleL;
@property(nonatomic, strong)RBCellModel *cellModel;

@end
@implementation RBCategoryTypeCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.backgroundColor = UIColor.clearColor;
        self.contentView.backgroundColor = UIColor.clearColor;
        
        self.container = [UIView.alloc initWithFrame:CGRectMake(0, 0, Zoom(115), Zoom(57))];
        [self.contentView addSubview:self.container];
        [self.container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(0);
            make.size.mas_equalTo(self.container.size);
        }];
        
        self.lineView = UIView.new;
        [self.lineView rbSetCornerRadius:Zoom(2)];
        self.lineView.backgroundColor = [UIColor colorWithHexString:@"#518CFF"];
        [self.container addSubview:self.lineView];
        [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.centerY.mas_equalTo(0);
            make.width.mas_equalTo(Zoom(4));
            make.height.mas_equalTo(Zoom(19));
        }];
        
        self.titleL = UILabel.new;
        self.titleL.numberOfLines = 2;
        self.titleL.adjustsFontSizeToFitWidth = YES;
        self.titleL.textAlignment = NSTextAlignmentCenter;
        [self.container addSubview:self.titleL];
        [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(Zoom(12));
            make.right.mas_equalTo(-Zoom(12));
            make.centerY.mas_equalTo(0);
        }];
        
        [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(reloadEvent) name:RBCategoryTypeCellNoti object:nil];
    }
    return self;
}

- (void)dealloc
{
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

- (void)reloadEvent
{
    [self setCellModel:self.cellModel];
}

- (void)setCellModel:(RBCellModel *)cellModel
{
    _cellModel = cellModel;
    RBCategoryTypeModel *model = cellModel.cellData;
    self.lineView.hidden = model.index != model.selectedIndex;
    self.titleL.text = model.title;
    self.titleL.textColor = model.index == model.selectedIndex? [UIColor colorWithHexString:@"#1A1A1A"]: [UIColor colorWithHexString:@"#3C3C3C"];
    self.titleL.font = model.index == model.selectedIndex? [UIFont boldSystemFontOfSize:Zoom(14)]: [UIFont systemFontOfSize:Zoom(13)];
    self.container.layer.mask = nil;
    if (model.index == model.selectedIndex)
    {
        self.container.backgroundColor = UIColor.whiteColor;
    }
    else
    {
        self.container.backgroundColor = [UIColor colorWithHexString:@"#F3F3F3"];
        if (model.index == model.selectedIndex - 1)
        {
            [self.container setRounderWithRectCorner:UIRectCornerBottomRight radius:Zoom(12)];
        }
        else if (model.index == model.selectedIndex + 1)
        {
            [self.container setRounderWithRectCorner:UIRectCornerTopRight radius:Zoom(12)];
        }
    }
}

@end

@interface RBCategoryTypeView()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, assign)NSInteger selectedIndex;

@end

@implementation RBCategoryTypeView

#pragma mark - System

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        
    }
    return self;
}

#pragma mark - Private

#pragma mark - Event

- (void)selectItemAtIndex: (NSInteger)index
{
    if (index == self.selectedIndex)
    {
        return;
    }
    if(self.selectBlock)
    {
        self.selectBlock(index);
    }
    self.selectedIndex = index;
    RBGroupModel *group = self.dataSource.firstObject;
    for (RBCellModel *cellModel in group.cellModels)
    {
        RBCategoryTypeModel *model = cellModel.cellData;
        model.selectedIndex = index;
    }
    [NSNotificationCenter.defaultCenter postNotificationName:RBCategoryTypeCellNoti object:nil];
    
    CGRect frame = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    if(self.tableView.contentSize.height < self.tableView.frame.size.height)
    {
        return;
    }
    CGFloat centerY = frame.origin.y + frame.size.height / 2;
    CGPoint contentOffset = self.tableView.contentOffset;
    if(centerY - self.tableView.frame.size.height / 2 < 0)
    {
        contentOffset.y = 0;
    }
    else if(centerY + self.tableView.frame.size.height / 2 > self.tableView.contentSize.height)
    {
        contentOffset.y = self.tableView.contentSize.height - self.tableView.frame.size.height;
    }
    else
    {
        contentOffset.y = centerY - self.tableView.frame.size.height / 2;
    }
    [self.tableView setContentOffset:contentOffset animated:YES];
}

#pragma mark - UITableViewDataSource & Delegate

kRBTableViewDataSourceAndDelegate(self.dataSource);

#pragma mark - Setter

- (void)setData:(NSArray *)data
{
    _data = data;
    __weak typeof(self) weakSelf = self;
    [self.dataSource removeAllObjects];
    [self.dataSource addObject:({
        RBGroupModel *group = RBGroupModel.new;
        group.cellModels = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            for (NSInteger i = 0; i < data.count; i++)
            {
                RBCatModel *catModel = data[i];
                [arrayM addObject:({
                    RBCellModel *cellModel = RBCellModel.new;
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBCategoryTypeCell.class);
                    cellModel.cellHeight = Zoom(57);
                    cellModel.cellData = ({
                        RBCategoryTypeModel *model = RBCategoryTypeModel.new;
                        model.title = catModel.cate_name;
                        model.index = i;
                        model.selectedIndex = 0;
                        model;
                    });
                    cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                        [weakSelf selectItemAtIndex:indexPath.row];
                    };
                    cellModel;
                })];
            }
            arrayM;
        });
        group;
    })];
    [self.tableView reloadData];
}

#pragma mark - Getter

- (UITableView *)tableView
{
    if (!_tableView)
    {
        self.tableView = ({
            UITableView *view = [UITableView.alloc initWithFrame:CGRectZero style:UITableViewStylePlain];
            view.dataSource = self;
            view.delegate = self;
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            kRBIgnoreScrollViewInsetsAdjust(view);
            view.separatorStyle = UITableViewCellSeparatorStyleNone;
            view.tableFooterView = UIView.new;
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.top.mas_equalTo(0);
            }];
            view;
        });
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        self.dataSource = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
    }
    return _dataSource;
}

@end
